import config from './config'
import _ from 'love-u'

export let $setCache = (key, val) => {
	if (!key) throw 'key is required'
	if (_.isNullOrUndef(val)) throw 'val is required'
	if (typeof val === 'object') val = JSON.stringify(val)
	uni.setStorageSync(key, val)
}

export let $getCache = (key) => {
	let info = uni.getStorageSync(key)
	if (!info) return;
	try {
		// 尝试转换对象的hack写法，如果是普通字符串将会走catch返回出去
		return JSON.parse(info)
	} catch (error) {
		return info
	}
}

export let $removeCache = (key) => uni.removeStorageSync(key)
export let $getToken = () => $getCache(config.KEY_TOKEN)
export let $setToken = (token) => $setCache(config.KEY_TOKEN, token)

/**
 * 验证是否登录
 */
export let $checkLogin = () => !!$getToken()

/**
 * 将自己的用户信息缓存到本地
 * @returns 
 */
export let $cacheMyInfo = (userInfo) => $setCache(config.KEY_LOGIN_USER_INFO, userInfo)

/**
 * 获取本地缓存的信息,前提是登录时$cacheMyInfo
 * @returns 
 */
export let $getMyInfo = () => $getCache(config.KEY_LOGIN_USER_INFO)


export let $clearLoginInfo = () => {
	$removeCache(config.KEY_TOKEN)
	$removeCache(config.KEY_OPEN_ID)
	$removeCache(config.KEY_UNION_ID)
	$removeCache(config.KEY_LOGIN_USER_INFO)
	$removeCache(config.KEY_SESSION_KEY)
}